package cn.intotw.rdcj.core.compoment;

import cn.intotw.rdcj.core.constant.RedisKeyConstant;
import cn.intotw.rdcj.core.util.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * Created by Chenxiang
 *
 * @generator: IntelliJ IDEA
 * @description: 分布式Id生成组件，使用雪花算法
 * @project: rdcj
 * @package: cn.intotw.rdcj.core.compoment
 * @date: 2020年05月06日 16时34分
 */
@Component
@Slf4j
public class IdWorkderCompoment {
    private static SnowflakeIdWorker SNOWFLAKE_ID_WORKER = null;
    @Value("${spring.application.name}")
    String applicationName;
    @Autowired
    RedissonClient redissonClient;

    /**
     * 通过redis获取worderId，初始化Id生成器
     *
     * @param
     * @return void
     * @author Chenxiang
     * @date 2020/5/6 17:32
     **/
    @PostConstruct
    private void initIdWorker() {
        String incrKey = RedisKeyConstant.WORKER_ID_KEY_PREFIX.concat(applicationName);
        String redisIdKey = RedisKeyConstant.REDIS_CENTER_ID_KEY_PREFIX;
        long workerId = redissonClient.getAtomicLong(incrKey).addAndGet(1L);
        long redisId = redissonClient.getAtomicLong(redisIdKey).get();
        if (workerId > SnowflakeIdWorker.getMaxWorkerId()) {
            redissonClient.getAtomicLong(incrKey).getAndSet(0L);
        }
        //初始化，尝试去获取workderId以及dataCenterId。
        SNOWFLAKE_ID_WORKER = new SnowflakeIdWorker(workerId%SnowflakeIdWorker.getMaxWorkerId(), redisId);
    }

    /**
     * 获取生成的下一个Id
     *
     * @param
     * @return java.lang.Long
     * @author Chenxiang
     * @date 2020/5/6 17:35
     **/
    public Long nextId() {
        return SNOWFLAKE_ID_WORKER.nextId();
    }
}
